package com.sunny.ynhz.api.retrofitUtil;
import android.util.Log;

import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.lang.reflect.Type;
import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by Administrator on 2016-10-11.
 */
public class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    Gson gson;
    Type type;

    public GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        Log.e("hu",response);
        value.close();
        try {
            JSONObject jsonObject = new JSONObject(response);
            int code = jsonObject.getInt("code");
            if (code == 0) {
                throw new RuntimeException("--"+jsonObject.getString("msg"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {

            T responseBody = getResponseBody(response);

            return responseBody;
//            }
//
        } finally {
        }
    }

    private T getResponseBody(String response) {

        if (type instanceof Class) {
            Class clazz = (Class) type;

            if (clazz.equals(JSONObject.class)) {//如果返回类型 为JsonObject
                try {
                    return (T) new JSONObject(response);
                } catch (JSONException e) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        return (T) jsonObject.put("src", response);
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                }
            }
            if (clazz.equals(JSONArray.class)) {
                try {
                    return (T) new JSONArray(response);
                } catch (JSONException e) {
                }
            }
        }
        return gson.fromJson(response, type);
    }
}
